package cn.wolfcode.luowowo.mgrsite.listener;

import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.domain.TravelStatisVO;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * spring容器启动监听器
 * 用来监听实现Redis数据初始化
 */
@Component
public class TravelRedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Reference
    private ITravelService travelDetailService;
    @Reference
    private ITravelStatisRedisService statisRedisService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("---------开始进行游记的Redis初始化------------");

        //从MySQL里获取所有的攻略明细数据
        List<Travel> list = travelDetailService.list();
        TravelStatisVO vo = null;
        for (Travel detail : list) {
            //这里判断一下,如果数据同步的时候发现Redis里面已经有这个key了就跳过,不然可能会造成数据丢失
            if(statisRedisService.isTravelStatisVOEsixt(detail.getId())){
                continue; //跳过此次循环
            }
            vo = new TravelStatisVO();
            //遍历添加到Redis里
            try {
                BeanUtils.copyProperties(vo,detail);
                //不同的字段属性需要我们自己设置
                vo.setDestId(detail.getDest().getId());
                vo.setDestName(detail.getDest().getName());
                vo.setTravelId(detail.getId());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            //设置vo到Redis里面
            statisRedisService.setTravelStatisVO(vo);
        }
        System.out.println("---------游记的Redis初始化结束------------");
    }
}
